package cate.game.pvp.pointrace;

import cate.game.GameBody;
import cate.game.db.SaveConstants;
import cate.game.framework.ModuleMan;
import cate.game.framework.ThreadShare;
import cate.game.pvp.pointrace.handler.LocalPointRaceHandler;
import cate.game.pvp.pointrace.handler.PointRaceHandler;
import cate.game.util.IntervalCounter;
import lombok.Getter;

import java.util.concurrent.ExecutorService;

import static cate.game.pvp.pointrace.handler.PointRaceHandler.ofLocal;

public class PointRaceManager extends ModuleMan {

    public static final String MODULE_NAME = "point-race";
    @Getter
    private final PointRaceDataManager dataManager = new PointRaceDataManager();
    @Getter
    private final PointRaceSimulatorManager simulatorManager
            = new PointRaceSimulatorManager(
            this.getDataManager()::getData,
            this.getDataManager()::getRankRwdOperation,
            this.getDataManager()::getRankHandler,
            this.getDataManager()::getExcelQueryOperation,
            this.getDataManager()::getPsOperation,
            this.getDataManager()::getChallenge
    );
    private final PointRaceTimerModule timerModule
            = new PointRaceTimerModule(
            this::getDataManager,
            this::getSimulatorManager
    );
    @Getter
    private final PointRaceMessagingModule messagingModule = new PointRaceMessagingModule();
    @Getter
    private LocalPointRaceHandler localHandler;

    public PointRaceHandler getHandler() {
        return this.localHandler;
    }

    public PointRaceHandler getEventHandler() {
        return this.localHandler;
    }

    @Override
    public void initIndependent(GameBody game) throws Exception {
        super.initIndependent(game);
        this.dataManager.initIndependent(game);
        this.simulatorManager.initIndependent(game);
        this.timerModule.initIndependent(game);
        this.messagingModule.initIndependent(game);
    }

    @Override
    public void initDependent() throws Exception {
        this.dataManager.initDependent();
        this.simulatorManager.initDependent();

        this.localHandler = ofLocal(game, this.dataManager);

        this.timerModule.initDependent();
        this.messagingModule.initDependent();
    }

    private final IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.PVP_SAVE_SECONDS);
    public void tick() {
        this.timerModule.tick();
        if (saveTrigger.trigger()) {
            this.dataManager.save();
        }
    }

    @Override
    public void shutdown() {
        super.shutdown();
        this.timerModule.shutdown();
        this.messagingModule.shutdown();
        this.simulatorManager.shutdown();
        this.dataManager.shutdown();
    }

    public static ExecutorService getExecutor() {
        return ThreadShare.instance().getExecutor(MODULE_NAME.hashCode());
    }
}
